<!--
 * Copyright © 2025 上海火金网络科技有限公司. All rights reserved.
 * App Product Config Modal - 应用产品配置模态框
 *
 * 功能：参考AppChannelConfigModal的布局，实现应用级别的产品配置
 * 版本：1.0.0
 * 参考：AppChannelConfigModal.vue - 应用渠道配置
 *
 * Website: https://www.anypay.com
-->

<template>
  <!-- 参考 AppChannelConfigModal.vue 的模态框结构 -->
  <a-modal
    :open="visible"
    :title="`${appInfo?.appName || '应用'} - 产品配置`"
    width="95%"
    :footer="null"
    @cancel="handleClose"
    @update:open="$emit('update:visible', $event)"
    class="app-product-config-modal"
  >
    <div class="product-config-workspace">
      <!-- 左侧：产品列表 - 参考商户渠道配置样式 -->
      <div class="product-sidebar">
        <div class="sidebar-header">
          <h3>支付产品配置</h3>
          <!-- 产品分类筛选 -->
          <div class="product-filter">
            <a-select
              v-model:value="selectedProductType"
              placeholder="选择产品类型"
              size="small"
              style="width: 100%"
              @change="handleProductTypeChange"
              allowClear
            >
              <a-select-option value="">全部类型</a-select-option>
              <a-select-option
                v-for="(config, type) in productTypeConfig"
                :key="type"
                :value="type"
              >
                {{ config.name }}
              </a-select-option>
            </a-select>
          </div>
        </div>

        <!-- 产品列表 - 完全参考应用商户渠道配置样式 -->
        <div class="product-list">
          <div
            v-for="product in filteredProducts"
            :key="product.productId"
            class="product-item"
            :class="{
              'active': selectedProductId === product.productId,
              'configured': isProductConfigured(product.productId)
            }"
            @click="handleProductSelect(product.productId)"
          >
            <div class="product-item-content">
              <div class="product-basic">
                <div class="product-icon">
                  <component :is="getProductIcon(product.productType)" />
                </div>
                <div class="product-info">
                  <div class="product-name">{{ product.productName }}</div>
                  <div class="product-code">{{ product.productCode }}</div>
                </div>
              </div>
              <div class="product-status">
                <a-tag
                  v-if="getProductConfig(product.productId)?.enabled"
                  color="success"
                  size="small"
                >
                  已启用
                </a-tag>
                <a-tag
                  v-else
                  color="default"
                  size="small"
                >
                  已禁用
                </a-tag>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧：配置详情 -->
      <div class="product-detail">
        <div v-if="loading && !initialized" class="loading-state">
          <a-skeleton active :paragraph="{ rows: 8 }" />
        </div>

        <div v-else-if="!selectedProductId" class="empty-state">
          <a-empty description="请选择要配置的产品" />
        </div>

        <div v-else class="product-detail-content">
          <div class="detail-header">
            <div class="product-title">
              <div class="product-icon-large">
                <component :is="getProductIcon(selectedProduct?.productType)" />
              </div>
              <div>
                <h3>{{ selectedProduct?.productName }}</h3>
                <p class="product-desc">{{ selectedProduct?.productDesc }}</p>
                <div class="product-meta">
                  <a-tag :color="getProductTypeColor(selectedProduct?.productType)">
                    {{ getProductTypeName(selectedProduct?.productType) }}
                  </a-tag>
                  <span class="amount-range">
                    金额范围：¥{{ selectedProduct?.minAmount }} - ¥{{ selectedProduct?.maxAmount }}
                  </span>
                </div>
              </div>
            </div>

            <div class="detail-actions">
              <div style="display: flex; gap: 16px; align-items: center;">
                <!-- 启用状态开关 -->
                <div class="product-status-control">
                  <span style="color: #666; font-size: 13px; margin-right: 8px;">启用状态：</span>
                  <a-switch
                    :checked="selectedProductConfig?.enabled || false"
                    @change="handleProductToggle(selectedProductId, $event)"
                    size="small"
                  />
                  <span style="color: #666; font-size: 12px; margin-left: 8px;">
                    {{ (selectedProductConfig?.enabled || false) ? '已启用' : '已禁用' }}
                  </span>
                </div>

                <!-- 保存按钮区域 -->
                <a-space>
                  <!-- 测试产品功能已删除 -->
                </a-space>
              </div>
            </div>
          </div>


          <!-- 渠道配置选择区域 -->
          <div class="channel-selection-container">
            <div class="section-header">
              <div class="section-title-area">
                <h4>选择该产品使用的支付渠道</h4>
                <p class="section-desc">
                  当前模式：
                  <a-tag :color="selectedChannelMode === 'DIRECT' ? 'blue' : 'green'" size="small">
                    {{ selectedChannelMode === 'DIRECT' ? '直连模式' : '服务商模式' }}
                  </a-tag>
                  <span class="mode-desc">（由应用配置决定）</span>
                </p>
              </div>
            </div>

            <!-- 渠道选择网格 -->
            <div v-if="availableChannels.length > 0" class="channel-grid">
              <div
                v-for="channel in availableChannels"
                :key="channel.channelCode"
                class="channel-card"
                :class="{
                  'selected': isChannelSelected(channel.channelCode),
                  'supported': isChannelSupported(channel, selectedChannelMode)
                }"
                @click="selectSingleChannel(channel.channelCode)"
              >
                <div class="channel-card-header">
                  <img
                    :src="channel.iconUrl || '/icons/default-channel.png'"
                    :alt="channel.channelName"
                    class="channel-icon"
                  />
                  <div class="channel-info">
                    <div class="channel-name">{{ channel.channelName }}</div>
                    <div class="channel-code">{{ channel.channelCode }}</div>
                  </div>
                  <div class="selection-indicator">
                    <a-radio
                      :checked="isChannelSelected(channel.channelCode)"
                      @click.stop="selectSingleChannel(channel.channelCode)"
                    />
                  </div>
                </div>

                <div class="channel-card-content">
                  <div class="support-info">
                    <a-tag
                      :color="isChannelSupported(channel, selectedChannelMode) ? 'success' : 'error'"
                      size="small"
                    >
                      {{ isChannelSupported(channel, selectedChannelMode) ? '支持' : '不支持' }}
                    </a-tag>
                  </div>

                  <!-- 配置状态 -->
                  <div class="config-status" v-if="isChannelSelected(channel.channelCode)">
                    <a-tag color="blue" size="small">
                      <SettingOutlined />
                      已选择
                    </a-tag>
                  </div>
                </div>
              </div>
            </div>

            <!-- 无可用渠道提示 -->
            <div v-else class="no-channels-tip">
              <a-empty description="暂无支持该产品的渠道">
                <template #image>
                  <ApiOutlined style="font-size: 48px; color: #d9d9d9;" />
                </template>
                <template #description>
                  <span style="color: #999;">
                    当前产品 "{{ selectedProduct?.productName }}" 在 {{ selectedChannelMode === 'DIRECT' ? '直连模式' : '服务商模式' }} 下暂无可用渠道
                  </span>
                </template>
              </a-empty>
            </div>

          </div>


          <!-- 固定保存按钮 -->
          <div class="fixed-save-button">
            <a-button
              type="primary"
              size="large"
              @click="handleSaveProductConfig(selectedProductId)"
              :loading="savingProducts.includes(selectedProductId)"
            >
              <template #icon>
                <SaveOutlined />
              </template>
              保存配置
            </a-button>
          </div>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { message } from 'ant-design-vue'
import {
  ApiOutlined,
  TeamOutlined,
  SaveOutlined,
  SettingOutlined,
  QrcodeOutlined,
  MobileOutlined,
  GlobalOutlined,
  CreditCardOutlined,
  AppstoreOutlined
} from '@ant-design/icons-vue'
import { paymentProducts, getProductTypeName, getProductTypeColor } from '@/mock/products'
import { paymentChannels } from '@/mock/channels'
import { appConfigs, mockLoadProductConfig, type AppConfig } from '@/mock/appconfigs'
import type { PaymentProduct } from '@/mock/products'
import { apiUnifiedChannelConfigEdit, apiUnifiedChannelConfigFetchList, apiUnifiedChannelConfigAdd } from '@/miaoma/unifiedchannelconfig/api'

// 使用真实API，不启用mock模式
// setUseMockData(true)

// 产品配置接口
interface AppProductConfig {
  id: string
  appId: string
  productId: string
  productCode: string
  enabled: boolean
  minAmount: number
  maxAmount: number
  timeoutMinutes: number
  notifyUrl: string
  returnUrl: string
  description: string
  selectedChannels: string[]
  channelMode: 'DIRECT' | 'PROVIDER'
  status: 'ACTIVE' | 'INACTIVE' | 'PENDING'
  createdTime: string
  updatedTime: string
}

// Props
interface Props {
  visible: boolean
  appInfo?: {
    appId: string
    appName: string
    merchantId: string
    connectMode?: string
  }
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  appInfo: () => ({ appId: '', appName: '', merchantId: '', connectMode: 'DIRECT' })
})

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  'success': []
}>()

// 响应式数据
const loading = ref(false)
const initialized = ref(false)
const selectedProductId = ref<string>('')
const selectedProductType = ref<string>('JSAPI') // 默认JSAPI支付类型
const actualProductConfigs = ref<any[]>([])
// 使用应用配置中的connectMode，不再允许用户选择
const selectedChannelMode = computed(() => {
  // 从应用配置中获取connectMode，INDIRECT映射为PROVIDER，DIRECT保持不变
  const appConnectMode = props.appInfo?.connectMode || 'DIRECT'
  return appConnectMode === 'INDIRECT' ? 'PROVIDER' : 'DIRECT'
})
const selectedChannels = ref<string[]>([])
const productConfigs = ref<AppProductConfig[]>([])
const savingProducts = ref<string[]>([])

// 添加调试日志函数
const addDebugLog = (level: 'info' | 'warn' | 'error' | 'debug', message: string) => {
  const timestamp = new Date().toLocaleTimeString()
  const logMessage = `[${timestamp}] [AppProductConfigModal-${level.toUpperCase()}] ${message}`
  // console.log(logMessage)
}

// Mock数据和函数
const mockProductConfigs: AppProductConfig[] = []

const mockGetAppProductConfigs = (appId: string) => {
  return Promise.resolve({ data: mockProductConfigs.filter(c => c.appId === appId) })
}

const mockSaveAppProductConfig = (config: Partial<AppProductConfig>) => {
  return Promise.resolve({ success: true, message: '保存成功' })
}


// 产品类型配置 - 根据数据库 t_pay_product_dict 表的 product_scene 字段定义
const productTypeConfig = {
  'APP': { name: 'APP支付', icon: 'MobileOutlined', scene: '1' },
  'H5': { name: 'H5支付', icon: 'GlobalOutlined', scene: '2' },
  'JSAPI': { name: 'JSAPI支付', icon: 'AppstoreOutlined', scene: '3' },
  'NATIVE': { name: '扫码支付', icon: 'QrcodeOutlined', scene: '4' },
  'CARD': { name: '刷卡支付', icon: 'CreditCardOutlined', scene: '5' },
  'MINIPROGRAM': { name: '小程序支付', icon: 'AppstoreOutlined', scene: '6' },
  'FACEPAY': { name: '刷脸支付', icon: 'ScanOutlined', scene: '7' }
}

// 计算属性
const filteredProducts = computed(() => {
  if (!selectedProductType.value) return paymentProducts
  return paymentProducts.filter(p => p.productType === selectedProductType.value)
})

const selectedProduct = computed(() => {
  return paymentProducts.find(p => p.productId === selectedProductId.value)
})

const selectedProductConfig = computed(() => {
  return getProductConfig(selectedProductId.value)
})

const currentConfig = computed(() => {
  return productConfigs.value.find(c => c.productId === selectedProductId.value)
})

const availableChannels = computed(() => {
  const filtered = paymentChannels.filter(channel => {
    // 首先检查渠道是否支持当前模式
    const supportMode = selectedChannelMode.value === 'DIRECT'
      ? channel.supportDirect
      : channel.supportProvider

    if (!supportMode) {
      return false
    }

    // 如果有选中的产品，则只显示支持该产品的渠道
    if (selectedProduct.value) {
      const isSupported = channel.supportedProducts.includes(selectedProduct.value.productCode)
      // console.log(`[渠道过滤] ${channel.channelName} 是否支持 ${selectedProduct.value.productName}(${selectedProduct.value.productCode}): ${isSupported}`)
      return isSupported
    }

    // 如果没有选中产品，显示所有支持当前模式的渠道
    return true
  })

  console.log(`[渠道过滤] 产品: ${selectedProduct.value?.productName || '未选择'}, 模式: ${selectedChannelMode.value}, 可用渠道数量: ${filtered.length}`)
  return filtered
})

// 方法
const handleClose = () => {
  emit('update:visible', false)
  productConfigs.value = []
  selectedProductId.value = ''
  selectedChannels.value = []
  initialized.value = false
}

const handleProductTypeChange = () => {
  // 重置选择，然后自动选择合适的产品
  selectedProductId.value = ''

  // 等待下一个tick后选择产品
  nextTick(() => {
    if (filteredProducts.value.length > 0) {
      let targetProductId = ''

      // 根据选择的产品类型，优先选择特定产品
      if (selectedProductType.value === 'H5') {
        // H5模式下优先选择微信H5支付
        const wechatH5Product = filteredProducts.value.find(p => p.productCode === 'WXPAY_H5')
        if (wechatH5Product) {
          targetProductId = wechatH5Product.productId
          addDebugLog('info', `🎯 切换到H5模式，优先选择微信H5支付: ${targetProductId}`)
        }
      } else if (selectedProductType.value === 'JSAPI') {
        // JSAPI模式下优先选择微信小程序支付
        const wechatJSAPIProduct = filteredProducts.value.find(p => p.productCode === 'WXPAY_JSAPI')
        if (wechatJSAPIProduct) {
          targetProductId = wechatJSAPIProduct.productId
          addDebugLog('info', `🎯 切换到JSAPI模式，优先选择微信小程序支付: ${targetProductId}`)
        }
      }

      // 如果没有找到特定产品，选择第一个
      if (!targetProductId) {
        targetProductId = filteredProducts.value[0].productId
        addDebugLog('info', `🎯 选择类型${selectedProductType.value}的第一个产品: ${targetProductId}`)
      }

      handleProductSelect(targetProductId)
    }
  })
}

const handleProductSelect = async (productId: string) => {
  selectedProductId.value = productId

  addDebugLog('info', `🎯 选择产品: ${productId}`)

  // 加载该产品的配置
  const config = getProductConfig(productId)
  addDebugLog('info', `📋 产品配置: ${JSON.stringify(config, null, 2)}`)

  // 检查之前选择的渠道是否支持新选择的产品
  const selectedProduct = paymentProducts.find(p => p.productId === productId)
  if (selectedProduct && config.selectedChannels && config.selectedChannels.length > 0) {
    addDebugLog('info', `🔍 检查渠道兼容性，当前配置的渠道: ${config.selectedChannels.join(', ')}`)

    // 过滤出仍然支持新产品的渠道 - 使用channelCode
    const validChannels = config.selectedChannels.filter(channelCode => {
      const channel = paymentChannels.find(c => c.channelCode === channelCode)
      const isValid = channel && channel.supportedProducts.includes(selectedProduct.productCode)
      addDebugLog('info', `   - 渠道 ${channelCode}: ${isValid ? '✅ 支持' : '❌ 不支持'}`)
      return isValid
    })

    selectedChannels.value = validChannels
    addDebugLog('info', `✅ 有效渠道: ${validChannels.join(', ')}`)

    // 如果没有有效渠道了，清空选择
    if (validChannels.length === 0) {
      selectedChannels.value = []
      addDebugLog('warn', `⚠️ 没有有效渠道，清空选择`)
    }
  } else {
    selectedChannels.value = config.selectedChannels || []
    addDebugLog('info', `📌 直接使用配置的渠道: ${selectedChannels.value.join(', ')}`)
    addDebugLog('info', `📌 config.selectedChannels: ${JSON.stringify(config.selectedChannels)}`)
  }

  await nextTick()
}

// 公共的产品配置保存函数
const saveProductConfigToUCC = async (productCode: string, configUpdate: any) => {
  console.log(`🔄 开始保存产品配置: ${productCode}`)

  // 1. 查找当前应用的UCC配置记录（应该只有一个）
  console.log(`📡 调用API获取配置列表...`)
  const response = await apiUnifiedChannelConfigFetchList({
    pageNumber: 1,
    pageSize: 1000
  })
  console.log(`📥 API响应:`, response)

  const appProductConfigs = response.data?.records?.filter((record: any) =>
    record.configType === 3 && // APP_PRODUCT_CHANNEL应用产品渠道
    record.ownerId === props.appInfo.appId
  ) || []
  console.log(`🔍 找到 ${appProductConfigs.length} 个应用产品配置记录`)

  // 2. 获取或创建应用的统一配置记录
  let appConfig = null
  if (appProductConfigs.length > 0) {
    appConfig = appProductConfigs[0]
    console.log(`📋 使用现有应用配置:`, appConfig.configId)
  }

  if (appConfig) {
    // 3. 更新现有的应用配置
    console.log(`📝 更新应用配置: ${appConfig.configId}`)

    const configData = JSON.parse(appConfig.configData || '{}')

    // 更新指定产品的配置
    configData[productCode] = {
      ...configData[productCode],
      ...configUpdate
    }

    const updateData = {
      configId: appConfig.configId,
      configType: 3,
      ownerId: props.appInfo.appId,
      ownerType: 2,
      channelCode: '',
      productCode: '',
      connectMode: 0,
      configData: JSON.stringify(configData)
    }

    console.log(`📤 发送更新请求:`, updateData)
    const updateResponse = await apiUnifiedChannelConfigEdit(appConfig.configId, updateData)
    console.log(`📥 更新响应:`, updateResponse)
    console.log(`✅ 更新应用配置成功`)
  } else {
    // 4. 创建新的应用配置记录
    console.log(`🆕 创建新的应用配置记录`)

    const configData = {
      [productCode]: configUpdate
    }

    const newConfigId = `UCC${Date.now()}`
    const newConfigData = {
      configId: newConfigId,
      configType: 3,
      ownerId: props.appInfo.appId,
      ownerType: 2,
      channelCode: '',
      productCode: '',
      connectMode: 0,
      configData: JSON.stringify(configData)
    }

    console.log(`📤 发送创建请求:`, newConfigData)
    const addResponse = await apiUnifiedChannelConfigAdd(newConfigData)
    console.log(`📥 创建响应:`, addResponse)
    console.log(`✅ 创建应用配置成功`)
  }
}

const handleProductToggle = async (productId: string, enabled: boolean) => {
  if (!props.appInfo?.appId || !productId) return

  const config = getProductConfig(productId)
  const product = paymentProducts.find(p => p.productId === productId)

  if (!product) {
    message.error('产品信息不存在')
    return
  }

  // 先更新本地状态，提供即时反馈
  const originalEnabled = config.enabled
  config.enabled = enabled
  config.updatedTime = new Date().toLocaleString()

  try {
    // 调用公共保存函数
    await saveProductConfigToUCC(product.productCode, {
      enabled: enabled,
      channelCode: config.selectedChannels?.[0] || '',
      extraInfo: {}
    })

    message.success(`${enabled ? '启用' : '禁用'}产品成功`)
    console.log(`✅ 产品状态保存成功: ${product.productCode} -> ${enabled}`)

  } catch (error) {
    console.error('❌ 保存产品状态失败:', error)
    message.error(`${enabled ? '启用' : '禁用'}产品失败: ${error.message || '请稍后重试'}`)

    // 恢复原始状态
    config.enabled = originalEnabled
    config.updatedTime = new Date().toLocaleString()
  }
}

// handleChannelModeChange方法已删除，因为现在使用应用配置的connectMode

// 单选渠道逻辑
const selectSingleChannel = (channelCode: string) => {
  const channel = paymentChannels.find(c => c.channelCode === channelCode)
  addDebugLog('info', `🎯 尝试选择渠道: ${channelCode} (${channel?.channelName})`)

  if (!isChannelSupported(channel, selectedChannelMode.value)) {
    addDebugLog('warn', `⚠️ 渠道 ${channelCode} 不支持当前模式 ${selectedChannelMode.value}`)
    message.warning('该渠道不支持当前模式')
    return
  }

  // 单选逻辑：清空现有选择，只选择当前渠道
  selectedChannels.value = [channelCode]
  addDebugLog('info', `✅ 已选择渠道: ${channelCode}`)
}

const clearChannelSelection = () => {
  selectedChannels.value = []
}

const handleSaveProductConfig = async (productId: string) => {
  if (!props.appInfo?.appId) return

  const config = getProductConfig(productId)
  const product = paymentProducts.find(p => p.productId === productId)

  if (!product) {
    message.error('产品信息不存在')
    return
  }

  // 验证配置
  if (!config.enabled) {
    message.warning('请先启用该产品')
    return
  }

  if (selectedChannels.value.length === 0) {
    message.warning('请至少选择一个支付渠道')
    return
  }

  savingProducts.value.push(productId)
  try {
    console.log(`📋 选择的渠道: ${selectedChannels.value.join(', ')}`)

    // 调用公共保存函数
    await saveProductConfigToUCC(product.productCode, {
      enabled: config.enabled,
      channelCode: selectedChannels.value[0] || '',
      extraInfo: {}
    })

    // 更新本地配置
    config.selectedChannels = [...selectedChannels.value]
    config.channelMode = selectedChannelMode.value
    config.updatedTime = new Date().toLocaleString()

    message.success('保存产品配置成功')
    console.log(`✅ 产品配置保存成功: ${product.productCode}`)
    emit('success')

  } catch (error) {
    console.error('❌ 保存产品配置失败:', error)
    message.error(`保存产品配置失败: ${error.message || '请稍后重试'}`)
  } finally {
    savingProducts.value = savingProducts.value.filter(id => id !== productId)
  }
}


const getProductConfig = (productId: string): AppProductConfig => {
  let config = productConfigs.value.find(c => c.productId === productId)

  if (!config) {
    const product = paymentProducts.find(p => p.productId === productId)

    // 尝试从实际配置中获取数据
    const actualConfig = actualProductConfigs.value.find(p => p.productCode === product?.productCode)
    const selectedChannelCodes = actualConfig?.channelMappings?.map((mapping: any) => mapping.channelCode) || []

    addDebugLog('info', `🆕 创建新的产品配置: ${productId}, 实际配置: ${JSON.stringify(actualConfig, null, 2)}`)
    addDebugLog('info', `🔄 提取的渠道代码: ${JSON.stringify(selectedChannelCodes)}`)

    config = {
      id: '',
      appId: props.appInfo?.appId || '',
      productId,
      productCode: product?.productCode || '',
      enabled: actualConfig?.enabled || false,
      minAmount: actualConfig?.minAmount || product?.minAmount || 0.01,
      maxAmount: actualConfig?.maxAmount || product?.maxAmount || 50000,
      timeoutMinutes: 30,
      notifyUrl: '',
      returnUrl: '',
      description: actualConfig?.description || '',
      selectedChannels: selectedChannelCodes.filter(Boolean),
      channelMode: selectedChannelMode.value,
      status: actualConfig?.enabled ? 'ACTIVE' : 'INACTIVE',
      createdTime: new Date().toLocaleString(),
      updatedTime: new Date().toLocaleString()
    }
    productConfigs.value.push(config)

    addDebugLog('info', `✅ 创建的产品配置: ${JSON.stringify(config, null, 2)}`)
  }

  return config
}

const isProductConfigured = (productId: string): boolean => {
  const config = productConfigs.value.find(c => c.productId === productId)
  return !!(config && config.enabled && config.selectedChannels.length > 0)
}

const getProductConfigStatus = (productId: string): boolean => {
  const config = productConfigs.value.find(c => c.productId === productId)
  return config?.enabled || false
}

const isChannelSelected = (channelCode: string): boolean => {
  const isSelected = selectedChannels.value.includes(channelCode)
  // 只对当前选中产品输出详细日志
  if (selectedProductId.value && selectedProduct.value?.productCode === 'WXPAY_H5') {
    addDebugLog('debug', `🔍 检查渠道选择状态: ${channelCode} -> ${isSelected ? '已选择' : '未选择'} (当前选择: ${selectedChannels.value.join(', ')})`)
  }
  return isSelected
}

const isChannelSupported = (channel: any, mode: string): boolean => {
  if (mode === 'DIRECT') {
    return channel?.supportDirect || false
  } else {
    return channel?.supportProvider || false
  }
}

const getChannelName = (channelCode: string): string => {
  const channel = paymentChannels.find(c => c.channelCode === channelCode)
  return channel?.channelName || channelCode
}

// 获取渠道的extraInfo信息
const getChannelExtraInfo = (channelCode: string, key: string): any => {
  if (!selectedProduct.value) return null

  // 从实际配置中查找当前产品的渠道映射
  const actualConfig = actualProductConfigs.value.find(p => p.productCode === selectedProduct.value?.productCode)
  if (!actualConfig || !actualConfig.channelMappings) return null

  // 找到对应渠道的配置
  const channelMapping = actualConfig.channelMappings.find((mapping: any) => mapping.channelCode === channelCode)

  // 根据key返回对应的值
  if (key === 'field1') return channelMapping?.merchantNo
  if (key === 'field2') return channelMapping?.feeRate
  if (key === 'enabled') return channelMapping?.enabled

  return null
}

const getProductIcon = (productType: string) => {
  const iconMap: { [key: string]: any } = {
    'NATIVE': QrcodeOutlined,
    'APP': MobileOutlined,
    'JSAPI': AppstoreOutlined,
    'H5': GlobalOutlined,
    'CARD': CreditCardOutlined
  }
  return iconMap[productType] || AppstoreOutlined
}

const getProductIconUrl = (productType: string): string => {
  const iconUrlMap: { [key: string]: string } = {
    'NATIVE': '/icons/qrcode-pay.png',
    'APP': '/icons/app-pay.png',
    'JSAPI': '/icons/mini-program-pay.png',
    'H5': '/icons/h5-pay.png',
    'CARD': '/icons/card-pay.png'
  }
  return iconUrlMap[productType] || '/icons/default-product.png'
}

const loadAppProductConfigs = async () => {
  if (!props.appInfo?.appId) return

  loading.value = true
  console.log(`🔄 开始加载应用产品配置: ${props.appInfo.appId}`)

  try {
    // 1. 从统一渠道配置API获取当前应用的所有配置
    const response = await apiUnifiedChannelConfigFetchList({
      pageNumber: 1,
      pageSize: 1000
    })

    console.log(`📥 统一渠道配置API响应:`, response)

    // 2. 过滤出当前应用的产品配置 (configType=3, ownerId=appId)
    const appProductConfigs = response.data?.records?.filter((config: any) =>
      config.configType === 3 && // APP_PRODUCT_CHANNEL应用产品渠道
      config.ownerId === props.appInfo.appId
    ) || []

    console.log(`🔍 找到 ${appProductConfigs.length} 个应用产品配置记录`)

    // 3. 解析配置数据，构建产品配置映射
    const productConfigMap = new Map<string, any>()

    appProductConfigs.forEach((config: any) => {
      try {
        const configData = JSON.parse(config.configData || '{}')
        console.log(`📋 解析配置数据:`, configData)

        // 遍历配置数据中的每个产品
        Object.keys(configData).forEach(productCode => {
          const productConfig = configData[productCode]
          productConfigMap.set(productCode, {
            configId: config.configId, // 保存UCC配置ID，用于后续更新
            productCode: productCode,
            enabled: productConfig.enabled || false,
            channelCode: productConfig.channelCode || null,
            extraInfo: productConfig.extraInfo || {}
          })
        })
      } catch (error) {
        console.error('❌ 解析配置数据失败:', error)
      }
    })

    console.log(`🗺️ 产品配置映射:`, productConfigMap)

    // 4. 为所有支付产品创建配置（已有配置使用真实数据，没有配置使用默认值）
    actualProductConfigs.value = []
    productConfigs.value = []

    paymentProducts.forEach(product => {
      const existingConfig = productConfigMap.get(product.productCode)

      // 构建actualProductConfigs格式（用于兼容现有逻辑）
      const actualConfig = {
        productCode: product.productCode,
        productName: product.productName,
        enabled: existingConfig?.enabled || false,
        channelMappings: existingConfig?.channelCode ? [{
          channelCode: existingConfig.channelCode,
          channelName: paymentChannels.find(c => c.channelCode === existingConfig.channelCode)?.channelName || existingConfig.channelCode,
          enabled: existingConfig?.enabled || false
        }] : [],
        minAmount: product.minAmount,
        maxAmount: product.maxAmount,
        description: ''
      }
      actualProductConfigs.value.push(actualConfig)

      // 构建productConfigs格式（组件内部使用）
      const internalConfig = {
        id: existingConfig?.configId || '', // 使用真实的UCC配置ID
        appId: props.appInfo?.appId || '',
        productId: product.productId,
        productCode: product.productCode,
        enabled: existingConfig?.enabled || false,
        minAmount: product.minAmount,
        maxAmount: product.maxAmount,
        timeoutMinutes: 30,
        notifyUrl: '',
        returnUrl: '',
        description: '',
        selectedChannels: existingConfig?.channelCode ? [existingConfig.channelCode] : [],
        channelMode: selectedChannelMode.value,
        status: 'INACTIVE', // 保留字段但不使用
        createdTime: new Date().toLocaleString(),
        updatedTime: new Date().toLocaleString()
      }
      productConfigs.value.push(internalConfig)

      console.log(`📦 产品 ${product.productCode}: 已有配置=${!!existingConfig}, 启用状态=${internalConfig.enabled}`)
    })

    console.log(`✅ 加载完成，共处理 ${productConfigs.value.length} 个产品配置`)

    // 5. 设置默认选择产品
    if (!selectedProductId.value && filteredProducts.value.length > 0) {
      let defaultProductId = ''

      // 优先选择JSAPI类型的微信支付
      if (selectedProductType.value === 'JSAPI') {
        const wechatJSAPIProduct = filteredProducts.value.find(p => p.productCode === 'WXPAY_JSAPI')
        if (wechatJSAPIProduct) {
          defaultProductId = wechatJSAPIProduct.productId
          console.log(`🎯 JSAPI模式下优先选择微信小程序支付: ${defaultProductId}`)
        }
      } else if (selectedProductType.value === 'H5') {
        const wechatH5Product = filteredProducts.value.find(p => p.productCode === 'WXPAY_H5')
        if (wechatH5Product) {
          defaultProductId = wechatH5Product.productId
          console.log(`🎯 H5模式下优先选择微信H5支付: ${defaultProductId}`)
        }
      }

      // 如果没有找到特定产品，选择第一个
      if (!defaultProductId) {
        defaultProductId = filteredProducts.value[0]?.productId || ''
        console.log(`🎯 默认选择第一个产品: ${defaultProductId}`)
      }

      if (defaultProductId) {
        await handleProductSelect(defaultProductId)
      }
    }

    initialized.value = true
  } catch (error) {
    console.error('❌ 加载产品配置失败:', error)
    message.error('加载产品配置失败')
  } finally {
    loading.value = false
  }
}

// 监听visible变化
watch(
  () => props.visible,
  async (visible) => {
    if (visible && props.appInfo?.appId) {
      await loadAppProductConfigs()
    } else if (!visible) {
      initialized.value = false
    }
  }
)

// 监听选中的渠道变化，同步到配置中
watch(selectedChannels, (newChannels) => {
  if (selectedProductId.value) {
    const config = getProductConfig(selectedProductId.value)
    config.selectedChannels = [...newChannels]
    config.channelMode = selectedChannelMode.value
    config.updatedTime = new Date().toLocaleString()
  }
}, { deep: true })
</script>

<style scoped>
/* 参考 AppChannelConfigModal.vue 的样式结构 */
.app-product-config-modal :deep(.ant-modal-body) {
  padding: 0;
}

.product-config-workspace {
  display: flex;
  height: 92vh;
  min-height: 800px;
  max-height: 1000px;
}

.product-sidebar {
  width: 360px;
  border-right: 1px solid #f0f0f0;
  background: #fafafa;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fff;
}

.sidebar-header h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  color: #333;
}

.mode-switcher {
  margin-bottom: 12px;
}

.mode-switcher :deep(.ant-radio-group) {
  width: 100%;
}

.mode-switcher :deep(.ant-radio-button-wrapper) {
  flex: 1;
  text-align: center;
  height: auto;
  padding: 8px 4px;
  font-size: 12px;
}

.product-filter {
  margin-bottom: 8px;
}

.product-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
}

.product-item {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.product-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.product-item.active {
  border-color: #1890ff;
  background: #e6f7ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.product-item.configured {
  border-left: 4px solid #52c41a;
}

.product-item-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.product-basic {
  display: flex;
  align-items: center;
  flex: 1;
}

.product-icon {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f6f8fa;
  border-radius: 6px;
  margin-right: 12px;
  font-size: 16px;
  color: #1890ff;
}

.product-info {
  flex: 1;
}

.product-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 2px;
}

.product-code {
  font-size: 12px;
  color: #666;
  font-family: monospace;
}

.product-type {
  margin-top: 4px;
}

.product-status {
  margin-left: 8px;
}

.product-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.empty-state {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.loading-state {
  flex: 1;
  padding: 24px;
}

.product-detail-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 24px;
  overflow-y: auto;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.product-title {
  display: flex;
  align-items: flex-start;
}

.product-icon-large {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f6f8fa;
  border-radius: 8px;
  margin-right: 16px;
  font-size: 24px;
  color: #1890ff;
}

.product-title h3 {
  margin: 0 0 4px 0;
  font-size: 20px;
  color: #333;
}

.product-desc {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
}

.product-meta {
  display: flex;
  align-items: center;
  gap: 12px;
}

.amount-range {
  color: #666;
  font-size: 13px;
}

.detail-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.product-status-control {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  background: #f6f8fa;
  border-radius: 6px;
  border: 1px solid #e1e8ed;
}

.channel-selection-container {
  margin-bottom: 24px;
  padding: 20px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.section-title-area h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #333;
}

.section-title-area .section-desc {
  margin: 0;
  color: #666;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.mode-and-desc {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 8px;
}

.mode-selection {
  display: flex;
  align-items: center;
  gap: 8px;
}

.mode-label {
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

.mode-desc {
  font-size: 12px;
  color: #999;
  margin-left: 8px;
}


.channel-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.channel-card {
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.channel-card:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.channel-card.selected {
  border-color: #1890ff;
  background: #e6f7ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
  position: relative;
}

.channel-card.selected::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(24, 144, 255, 0.05), rgba(24, 144, 255, 0.02));
  border-radius: 8px;
  pointer-events: none;
}

.channel-card:not(.supported) {
  opacity: 0.5;
  cursor: not-allowed;
}

.channel-card-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.channel-icon {
  width: 24px;
  height: 24px;
  object-fit: contain;
  margin-right: 8px;
}

.channel-info {
  flex: 1;
}

.channel-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.channel-code {
  font-size: 12px;
  color: #666;
  font-family: monospace;
}

.selection-indicator {
  margin-left: auto;
}

.channel-card-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.support-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.mode-label {
  font-size: 12px;
  color: #666;
}

.config-status {
  display: flex;
  align-items: center;
}

.no-channels-tip {
  padding: 40px 20px;
  text-align: center;
  background: #fafafa;
  border-radius: 8px;
  border: 1px dashed #d9d9d9;
}

.selection-summary {
  margin-top: 16px;
  padding: 12px;
  background: #fff;
  border-radius: 6px;
  border: 1px solid #e8e8e8;
}

.summary-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.summary-header h5 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.summary-content {
  margin-top: 8px;
}

.fixed-save-button {
  position: absolute;
  bottom: 20px;
  right: 20px;
  z-index: 1000;
}

/* 模式选择器样式 */
.mode-selection :deep(.ant-radio-group) {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  overflow: hidden;
}

.mode-selection :deep(.ant-radio-button-wrapper) {
  border: none;
  height: 32px;
  line-height: 30px;
  font-size: 13px;
  padding: 0 12px;
}

.mode-selection :deep(.ant-radio-button-wrapper:first-child) {
  border-radius: 6px 0 0 6px;
}

.mode-selection :deep(.ant-radio-button-wrapper:last-child) {
  border-radius: 0 6px 6px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .product-config-workspace {
    flex-direction: column;
    height: auto;
  }

  .product-sidebar {
    width: 100%;
    max-height: 300px;
  }

  .channel-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .mode-and-desc {
    align-items: flex-start;
  }
}

@media (max-width: 768px) {
  .detail-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .channel-grid {
    grid-template-columns: 1fr;
  }

  .mode-selection {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .mode-selection :deep(.ant-radio-button-wrapper) {
    font-size: 12px;
    padding: 0 8px;
  }
}

</style>